﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using bdnt_pets_system.Tools;
using System.Windows.Data;
using bdnt_pets_system_Entity;
using bdnt_pets_system.MyUserControls;
using System.Globalization;
using bdnt_pets_system.FailureServiceReference;
using System.Windows.Controls.Primitives;
using bdnt_pets_system.PageViews.FailuresTraking;
using bdnt_pets_system.Resources;

namespace bdnt_pets_system.PageViews.Failures
{
    public partial class FailureRecourdManagerControl : BaseUserControl
    {
        FailureServiceReference.FailureServiceClient faiClient;
        DataServiceReference.DataServiceClient dataClient;

        List<Tbl_StationMemebers> cuStationMemembers = null;
        int pageSize = SessionManager.PageSize;
        int currentPage = 1;

        //默认查询条件
        FRManagerControlPageCondition selectFailureInfo = new FRManagerControlPageCondition()
        {
            VINNo = MyStrings.qsrclsbm,
            PartName = MyStrings.qsrbjmc,
            FailureName = MyStrings.qsrgz
        };

        FRManagerControlPageCondition CuFRManagerControlPageCondition
        {
            get { return sConditon.DataContext as FRManagerControlPageCondition; }
            set { sConditon.DataContext = value; }
        }

        public FailureRecourdManagerControl()
        {
            InitializeComponent();
            dataClient = new DataServiceReference.DataServiceClient();
            faiClient = new FailureServiceReference.FailureServiceClient();
            InitData();
        }

        void faiClient_DeleteFailureRecordCompleted(object sender, DeleteFailureRecordCompletedEventArgs e)
        {
            QueryData();
        }

        void btnBack_Click(object sender, RoutedEventArgs e)
        {
            App.ToPrePage(this);
        }

        void InitEvent()
        {
            dataClient.GetStationMemebersByCoditionCompleted += new EventHandler<DataServiceReference.GetStationMemebersByCoditionCompletedEventArgs>(dataClient_GetStationMemebersByCoditionCompleted);
            faiClient.GetFailureRecordListByConditionCompleted += new EventHandler<FailureServiceReference.GetFailureRecordListByConditionCompletedEventArgs>(faiClient_GetFailureRecordListByConditionCompleted);
            faiClient.GetFailureRecordListByConditionCountCompleted += new EventHandler<FailureServiceReference.GetFailureRecordListByConditionCountCompletedEventArgs>(faiClient_GetFailureRecordListByConditionCountCompleted);
            btnSelect.Click += new RoutedEventHandler(btnSelect_Click);
            failurePageC.dpPage.PageIndexChanged += new EventHandler<EventArgs>(dpPage_PageIndexChanged);
            cbStationName.SelectionChanged += new SelectionChangedEventHandler(cbStationName_SelectionChanged);
            btnBack.Click += new RoutedEventHandler(btnBack_Click);
            faiClient.UpdateFailureRecordCompleted += new EventHandler<UpdateFailureRecordCompletedEventArgs>(faiClient_UpdateFailureRecordCompleted);
            faiClient.DeleteFailureRecordCompleted += new EventHandler<DeleteFailureRecordCompletedEventArgs>(faiClient_DeleteFailureRecordCompleted);
        }

        void InitData()
        {
            InitEvent();
            tbVINNo.Foreground = tbPartName.Foreground = tbFailureName.Foreground = new SolidColorBrush(Colors.Gray);

            tbVINNo.SetBinding(TextBox.TextProperty, new Binding("VINNo") { Mode = BindingMode.TwoWay });
            tbVINNo.Tag = selectFailureInfo.VINNo;
            tbPartName.SetBinding(TextBox.TextProperty, new Binding("PartName") { Mode = BindingMode.TwoWay });
            tbPartName.Tag = selectFailureInfo.PartName;
            tbFailureName.SetBinding(TextBox.TextProperty, new Binding("FailureName") { Mode = BindingMode.TwoWay });
            tbFailureName.Tag = selectFailureInfo.FailureName;

            CuFRManagerControlPageCondition = new FRManagerControlPageCondition()
            {
                VINNo = selectFailureInfo.VINNo,
                PartName = selectFailureInfo.PartName,
                FailureName = selectFailureInfo.FailureName
            };
            if (string.IsNullOrEmpty(SessionManager.CurrentUser.StationIds))
                return;
            dataClient.GetStationMemebersByCoditionAsync(SessionManager.CurrentUser.StationIds);
        }
        List<Tbl_DictInfo> FxDicts = new List<Tbl_DictInfo>();
        int cuStationId = 0;
        void dataClient_GetStationMemebersByCoditionCompleted(object sender, DataServiceReference.GetStationMemebersByCoditionCompletedEventArgs e)
        {
            cuStationMemembers = e.Result.ToList();
            var stations = HelpTools.DistinctList(cuStationMemembers.Select(p => new SimpleObject<int, string>()
            {
                Item1 = p.StationId,
                Item2 = SessionManager.IsCN_ZH ? p.StationName : p.en_StationName
            }).OrderBy(p => p.Item1).ToList()).ToList();
            stations.Insert(0, new SimpleObject<int, string>() { Item1 = 0, Item2 = MyStrings.qb });
            cuStationId = stations.FirstOrDefault() != null ? stations.FirstOrDefault().Item1 : 0;
            cbStationName.ItemsSource = stations;
            cbStationName.DisplayMemberPath = "Item2";
            cbStationName.SelectedValuePath = "Item1";
            cbStationName.SelectedIndex = 0;

            SystemServiceReference.SystemServiceClient sysClient = new SystemServiceReference.SystemServiceClient();
            sysClient.GetDictListByPidCompleted += new EventHandler<SystemServiceReference.GetDictListByPidCompletedEventArgs>(sysClient_GetDictListByPidCompleted);
            sysClient.GetDictListByPidAsync(15);
            sysClient.CloseAsync();
        }

        int isFx = -1;
        int isZx = -1;
        int checkUserId = 0;
        void QueryData()
        {
            if (cbEmpName.SelectedValue != null)
            {
                var sv = cbEmpName.SelectedValue.ToString();
                checkUserId = Int32.Parse(sv);
            }

            isFx = (rbFxAll.IsChecked.Value ? -1 : (rbFxYes.IsChecked.Value ? 1 : 0));
            //isZx = (rbZzAll.IsChecked.Value ? -1 : (rbZzYes.IsChecked.Value ? 1 : 0));
            
            faiClient.GetFailureRecordListByConditionCountAsync(CuFRManagerControlPageCondition.VINNo == selectFailureInfo.VINNo ? "" : CuFRManagerControlPageCondition.VINNo,
               "", CuFRManagerControlPageCondition.PartName == selectFailureInfo.PartName ? "" : CuFRManagerControlPageCondition.PartName,
                 CuFRManagerControlPageCondition.FailureName == selectFailureInfo.FailureName ? "" : CuFRManagerControlPageCondition.FailureName,
                 cuStationId, checkUserId, dpBCheckDate.SelectedDate, dpECheckDate.SelectedDate, isFx, isZx, null, null, "", 0);

        }
        void btnSelect_Click(object sender, RoutedEventArgs e)
        {
            QueryData();
        }

        void dpPage_PageIndexChanged(object sender, EventArgs e)
        {
            currentPage = failurePageC.PageIndex + 1;

            faiClient.GetFailureRecordListByConditionAsync(CuFRManagerControlPageCondition.VINNo == selectFailureInfo.VINNo ? "" : CuFRManagerControlPageCondition.VINNo,
                "", CuFRManagerControlPageCondition.PartName == selectFailureInfo.PartName ? "" : CuFRManagerControlPageCondition.PartName,
                 CuFRManagerControlPageCondition.FailureName == selectFailureInfo.FailureName ? "" : CuFRManagerControlPageCondition.FailureName,
                 cuStationId, checkUserId, dpBCheckDate.SelectedDate, dpECheckDate.SelectedDate, isFx, isZx, pageSize, currentPage, null, null, "", 0);
        }

        void faiClient_GetFailureRecordListByConditionCountCompleted(object sender, FailureServiceReference.GetFailureRecordListByConditionCountCompletedEventArgs e)
        {
            failurePageC.LoadPages(e.Result, pageSize);
        }

        void faiClient_GetFailureRecordListByConditionCompleted(object sender, FailureServiceReference.GetFailureRecordListByConditionCompletedEventArgs e)
        {
            var cure = e.Result.ToList();
            var cures = cure.Select(p => new SimpleObject<Tbl_FailureRecord, List<Tbl_DictInfo>>() { Item1 = p, Item2 = FxDicts });
            //var cures = cure.Select(p => new SimpleObject<Tbl_FailureRecord, List<Tbl_DictInfo>, bool>() { Item1 = p, Item2 = FxDicts, Item3 = false });
            //var cures = cure.Select(p => new SimpleObject<Tbl_FailureRecord, List<Tbl_DictInfo>, string>() { Item1 = p, Item2 = FxDicts, Item3 = "" });
            gdList.ItemsSource = cures;
        }

        void sysClient_GetDictListByPidCompleted(object sender, SystemServiceReference.GetDictListByPidCompletedEventArgs e)
        {
            FxDicts = e.Result.OrderBy(p => p.Sequence).ToList();
            QueryData();

        }
        void cbStationName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cuo = sender as ComboBox;
            if (cuo.SelectedValue == null)
                return;
            var sv = cuo.SelectedValue.ToString();
            cuStationId = Int32.Parse(sv);
            if (cuStationMemembers == null || cuStationMemembers.Count < 1)
                return;

            var emps = HelpTools.DistinctList(cuStationMemembers.Where(p => p.StationId.ToString() == sv).Select(p => new SimpleObject<int, string>()
            {
                Item1 = p.EmpId,
                Item2 = p.EmpName
            }).OrderBy(p => p.Item1).ToList()).ToList();
            emps.Insert(0, new SimpleObject<int, string>() { Item1 = 0, Item2 = MyStrings.qb });
            cbEmpName.ItemsSource = emps;
            cbEmpName.DisplayMemberPath = "Item2";
            cbEmpName.SelectedValuePath = "Item1";
            cbEmpName.SelectedIndex = emps.Count > 0 ? 0 : -1;
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            var cuhb = sender as HyperlinkButton;
            var cuo = (cuhb.Tag as Tbl_FailureRecord);
            var cuSp = (cuhb.Parent as StackPanel);
            ComboBox cb = cuSp.Children.FirstOrDefault(p => p is ComboBox) as ComboBox;
            cb.Visibility = System.Windows.Visibility.Visible;
            cuhb.Visibility = System.Windows.Visibility.Collapsed;
        }

        void faiClient_UpdateFailureRecordCompleted(object sender, UpdateFailureRecordCompletedEventArgs e)
        {
            if (e.Result)
            {
                //(e.UserState as SimpleObject<Tbl_FailureRecord, List<Tbl_DictInfo>, string>).Item3 = "保存成功";
                //gdList.UpdateLayout();
                (e.UserState as HyperlinkButton).IsEnabled = true;
                (e.UserState as HyperlinkButton).Content = MyStrings.bc;
                QueryData();
            }
        }

        private void cbFx_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cuo = (sender as ComboBox);
            if (cuo.SelectedValue == null)
                return;
            var cuFr = (cuo.Tag as SimpleObject<Tbl_FailureRecord, List<Tbl_DictInfo>>);
            if (cuFr == null)
                return;

            if (cuo.SelectedValue.ToString() != "0")
                cuFr.Item1.RepairStatus = true;
            else cuFr.Item1.RepairStatus = false;
            cuFr.Item1.RepairResultText = (cuo.SelectedItem as Tbl_DictInfo).DictName;
        }

        private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
        {
            var cuhb = sender as HyperlinkButton;
            cuhb.Content = MyStrings.bcz + "...";
            cuhb.IsEnabled = false;

            //var dgCurrentData = (cuhb.Tag as SimpleObject<Tbl_FailureRecord, List<Tbl_DictInfo>, string>);
            var dgCurrentData = (cuhb.Tag as SimpleObject<Tbl_FailureRecord, List<Tbl_DictInfo>>);
            faiClient.UpdateFailureRecordAsync(dgCurrentData.Item1, cuhb);
        }

        private void gdList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (e.RemovedItems.Count == 0)
            //    return;
            //var cuads = e.AddedItems.OfType<SimpleObject<Tbl_FailureRecord, List<Tbl_DictInfo>, string>>();
            //var cuA = cuads.FirstOrDefault();   
            //var cuos = e.RemovedItems.OfType<SimpleObject<Tbl_FailureRecord, List<Tbl_DictInfo>, string>>();
            //var cuo = cuos.FirstOrDefault();
            //if (cuA.Item1.Id == cuo.Item1.Id)
            //    return;
            //cuo.Item3 = "保存中...";
            //faiClient.UpdateFailureRecordAsync(cuo.Item1, cuo);
        }

        private void HyperlinkButton_Click_2(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show(MyStrings.qdyscm, MyStrings.ts, MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                return;
            var cuhb = sender as HyperlinkButton;
            var cuObjId = Int32.Parse(cuhb.Tag.ToString());
            faiClient.DeleteFailureRecordAsync(cuObjId);
        }

    }

    public class FRManagerControlPageCondition
    {
        public string VINNo { get; set; }
        public string PartName { get; set; }
        public string FailureName { get; set; }
    }
}
